package com.tssup.fesco.common.utils;

import com.tssup.fesco.common.cache.Cache;
import com.tssup.fesco.common.exeception.CacheException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
/**
 * 单号工具类
 *
 * @author shuchang.liao
 * @create 2017-03-11 13:48
 */
public class NoUtil {
    private static Logger logger = LoggerFactory.getLogger(NoUtil.class);

    /**
     *
     * @param date  创建订单时间
     * @param cache redis接口
     * @param orderId  操作的redis 自增KEY
     * @return
     */
    public static String generateOrderNo(Date date,Cache cache,String orderId)  {
        String no=DateUtils.convertDate2String(DateUtils.DATETIME_WITHOUT_MIN_FORMAT,date);
        String min=DateUtils.convertDate2String(DateUtils.DATETIME_MIN_FORMAT,date);
        try{
            Object object=cache.get(orderId,String.class);
            if (object==null){
                cache.setex(orderId,60,min+String.format("%06d",1));
                no+=cache.get(orderId,String.class).toString();
            }else{
                if(!object.toString().substring(0,2).equals(min)){
                    cache.setex(orderId,60,min+String.format("%06d",1));
                    no+=min+String.format("%06d",1);
                }else{
                    cache.set(orderId,min+(String.valueOf(String.format("%06d",Integer.parseInt(object.toString().substring(2))+1))));
                    no+=cache.get(orderId,String.class);
                }

            }
        }catch (CacheException e){
            logger.error("单号获取出错:", e);
        }

        return no;
    }

}
